<?php

namespace App\Trip\Wechat\Pay\RefundRes;

use Carbon\Carbon;
use Exception;

class RefundResult
{
    private mixed $result;

    public function __construct($result)
    {
        $this->setResult($result);
    }

    private function setResult($result): void
    {
        if (is_string($result)) {
            $result = json_decode($result, true);
        }
        $this->result = $result;
    }

    public function getMchId(): string
    {
        return $this->mchid;
    }

    /**
     * 系统支付单号
     *
     * @return mixed
     */
    public function getOutTradeNo(): string
    {
        return $this->out_trade_no;
    }

    /**
     * 外部退款单号
     *
     * @return mixed
     */
    public function getOutRefundNo(): string
    {
        return $this->out_refund_no;
    }

    /**
     * 外部退款id
     *
     * @return mixed
     */
    public function getOutRefundId(): string
    {
        return $this->refund_id;
    }

    /**
     * 微信单号
     *
     * @return mixed
     */
    public function getTransactionId(): string
    {
        return $this->transaction_id;
    }

    public function isSuccess(): bool
    {
        return $this->getRefundState() == "SUCCESS";
    }

    /**
     * 退款状态
     * SUCCESS：退款成功
     * CLOSED：退款关闭
     * ABNORMAL：退款异常，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，可前往【商户平台—>交易中心】，手动处理此笔退款
     *
     * @return mixed
     */
    public function getRefundState()
    {
        return $this->refund_status;
    }

    /**
     * 退款入账账户
     *
     * @return string
     */
    public function getReceivedAccount(): string
    {
        return $this->user_received_account;
    }

    /**
     * 退款成功时间
     *
     * @return string
     */
    public function getRefundedAt(): string
    {
        return Carbon::parse($this->success_time)->toDateTimeString();
    }

    /**
     * 订单金额
     *
     * @return float
     */
    public function getTotalAmount(): float
    {
        return bcdiv($this->amount['total'], 100, 2);
    }

    /**
     * 退款金额
     *
     * @return float
     */
    public function getRefundAmount(): float
    {
        return bcdiv($this->amount['refund'], 100, 2);
    }

    /**
     * 用户支付金额
     *
     * @return float
     */
    public function getPayerTotalAmount(): float
    {
        return bcdiv($this->amount['payer_total'], 100, 2);
    }

    /**
     * 用户退款金额
     *
     * @return float
     */
    public function getPayerRefundAmount(): float
    {
        return bcdiv($this->amount['payer_refund'], 100, 2);
    }

    /**
     * @throws Exception
     */
    public function __get(string $name)
    {
        if (isset($this->result[$name])) {
            return $this->result[$name];
        }

        if (isset($this->result["code"]) && isset($this->result["message"])) {
            throw new Exception("{$this->result["message"]}", 404);
        }
        throw new Exception("属性：{$name}不存在");
    }
}